#include "umessage.h"
#include <iostream>
#include <QTextEdit>
#include <QLabel>
#include <QTextBlock>
UMessage::UMessage(QWidget *parent,QString text,QString time, bool self)
	: QWidget(parent)
	, m_pEditText(new QTextEdit(this))
	, m_pIp(new QLabel(this))
	, m_pTime(new QLabel(this))
	, m_isSelf(self)
{
	setAttribute(Qt::WA_StyledBackground, true);

	m_pEditText->setText(text);
	m_pTime->    setText(time);
	m_pEditText->setReadOnly(true);//设置只读
	m_pEditText->setStyleSheet(R"(QTextEdit{background-color:#EBEBEB;border:none;font-family:微软雅黑;font-size: 12px;})");
	m_pIp->      setStyleSheet(R"(QLabel{font-family:微软雅黑;font-size: 12px;})");

	QFontMetrics fontMetrics(m_pEditText->font());                          //获取字体的高度和长度，调整消息显示栏的大小
	QStringList lines = text.split('\n');
	int maxWidth = 0;
	for (const QString& line : lines) {
		int lineWidth = fontMetrics.horizontalAdvance(line);
		if (lineWidth > maxWidth) maxWidth = lineWidth;}
	QRect textRect = fontMetrics.boundingRect(m_pEditText->toPlainText());

	m_pEditText-> resize(maxWidth + 10, std::min(410, 10 + textRect.height() * m_pEditText->document()->lineCount()));
	m_pIp->       resize(48, 20);
	m_pTime->	  resize(50, 20);
	this->		  resize(std::max(100, m_pEditText->width()), m_pEditText->height() + 40);

	if (m_isSelf == true)
	{
		m_pIp->setText(" 客户端");
		m_pEditText->move(UMessage::width()- m_pEditText->width(), 20);
		m_pIp->move(UMessage::width() - m_pIp->width(), 0);
		m_pTime->move(0, m_pEditText->height() + 40 - m_pTime->height());
		m_pEditText->setStyleSheet(R"(QTextEdit{background-color:#89D961;border:none;})");
	}
	else
	{
		m_pIp->setText(" 服务器");
		m_pEditText->move(0, 20);
		m_pIp->move(0, 0);
		m_pTime->move(UMessage::width()- m_pTime->width(), m_pEditText->height() + 40 - m_pTime->height());
		m_pEditText->setStyleSheet(R"(QTextEdit{background-color:#EBEBEB;border:none;})");
	}

}

UMessage::~UMessage()
{}


